<?php
/**
 * Created by PhpStorm.
 * User: Keter
 * Date: 2016/8/3
 * Time: 16:55
 */
class UserQuery extends DatabaseBase
{
    /**
     * 查询用户信息的一般字段
     * @var array
     */
    public static $userFields = array(
        'uid',      'username',  'sex',         'nickname',
        'avatar',   'address',   'status',      'platform',
        'channelID', 'ver',      'freeDiamond', 'paidDiamond',
        'registerIP', 'registerTime',
    );

    /**
     * 获取用户所在房间信息
     * @param $redis
     * @param $uid
     * @param $platform
     * @return array
     */
    public function queryRoomInfo($uid, $platform)
    {
        $result = array();
        $roomRedis = $this->redis('room_status');

        if ( ! $roomID = (int) $this->redis('status')->hget('uid2roomID', $uid)) {
            $roomID = (int) $this->redis('room_status')->hMget('UR:' . $uid, ['roomID'])['roomID'];
        }

        if ($roomID && $roomRedis->exists('R:' . $roomID)) {
            $roomInfo = $roomRedis->hMget('R:' . $roomID, array('serverID'));
            if ($roomInfo['serverID'] && $this->redis->exists('S:' . $roomInfo['serverID'])) {
                $serverInfo = $this->redis->HMget('S:' . $roomInfo['serverID'], array('domain', 'ip', 'lanIP', 'serverPort'));
                //IOS需要域名
                if ($platform == GlobalConfig::PLATFORM_IOS) {
                    $serverIP = $serverInfo['domain'];
                } else {
                    $serverIP = $serverInfo['lanIP'];
                }
                $result = array(
                    'roomID' => (integer)$roomID,
                    'serverIP' => $serverIP,
                    'serverPort' => (integer)$serverInfo['serverPort'],
                    'serverID' => $roomInfo['serverID']
                );
            }
        }

        return $result;
    }

    /**
     * 获取用户信息
     * @return array
     */
    public function getUserInfo($uid, $platform, $moreFields = array())
    {
        $fields = array_merge(self::$userFields, $moreFields);
        $userInfo = $this->redis('user_info')->hMget('U:' . $uid, $fields);
        $userInfo['IP'] = IP::getClientIP();
        $roomInfo = $this->queryRoomInfo($userInfo['uid'], $platform);

        if ($roomInfo) {
            $userInfo['roomInfo'] = $roomInfo;
        }

        $userInfo['diamond'] = (integer)$userInfo['freeDiamond'] + (integer)$userInfo['paidDiamond'];

        return $userInfo ? $userInfo : array();
    }

    /**
     * 向用户钻石变动消息队列推入消息
     * @param $data
     * @param $msg
     * @return mixed
     */
    public function pushDiamondChageMsg($data, $msg)
    {
        $result = [
            'way' => $data['way'],
            'amount' => $data['amount'],
            'desc' => sprintf($msg, $data['diamond'])
        ];

        $result = json_encode($result, JSON_UNESCAPED_UNICODE);
        $ret = $this->redis('room_status')->lpush('UDC:' . $data['uid'], $result);

        return $ret;
    }
}